package br.com.manutencao.repositories;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;

import br.com.manutencao.entities.Chamado;

public class ChamadoRepository implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	private EntityManager em = Persistence.createEntityManagerFactory("jsf")
			.createEntityManager();

	public void adiciona(Chamado chamado) {
		em.getTransaction().begin();
		em.persist(chamado);
		em.getTransaction().commit();
		em.close();
	}
	
	public void altera(Chamado chamado){
		em.getTransaction().begin();
		em.merge(chamado);
		em.getTransaction().commit();
	}
	
	public void delete(Chamado chamado){
		em.getTransaction().begin();
		em.remove(chamado);
		em.getTransaction().commit();
	}

	@SuppressWarnings("all")
	public Collection<Chamado> buscaTodos(){
		Collection<Chamado> chamados = new ArrayList<Chamado>();
		
		em.getTransaction().begin();
		Query query = em.createNamedQuery("Chamado.findAll");
		chamados = query.getResultList();
		em.getTransaction().commit();
		
		return chamados;
	}
	
	public Collection<Chamado> buscaTodosOpen(){
		Collection<Chamado> chamadosOpen = new ArrayList<Chamado>();
		
		em.getTransaction().begin();
		Query query = em.createNamedQuery("Chamado.findOpen");
		chamadosOpen = query.getResultList();
		em.getTransaction().commit();
		
		return chamadosOpen;
	}
	
	public Chamado buscaPorId(int id){
		em.getTransaction().begin();
		Chamado chamado = em.find(Chamado.class, id);
		em.getTransaction().commit();
		
		return chamado;
	}

}
